/**
 * 备份管理路由
 * Backup Management Routes
 */

const express = require('express');
const { body, query, validationResult } = require('express-validator');
const BackupService = require('../services/backup');
const logger = require('../utils/logger');
const scheduler = require('../utils/scheduler');

const router = express.Router();
const backupService = new BackupService();

/**
 * 权限检查中间件 - 只有管理员可以访问备份功能
 * Permission check middleware - Only admins can access backup functions
 */
const adminOnly = (req, res, next) => {
  if (req.user.role !== 'admin') {
    return res.status(403).json({
      success: false,
      message: '权限不足，只有管理员可以访问备份功能 / Insufficient permissions, only admins can access backup functions'
    });
  }
  next();
};

/**
 * 获取备份列表
 * GET /api/backup/list
 */
router.get('/list', adminOnly, async (req, res) => {
  try {
    const backups = await backupService.getBackupList();
    
    res.json({
      success: true,
      data: {
        backups: backups.map(backup => ({
          fileName: backup.fileName,
          size: backup.size,
          formattedSize: backupService.formatFileSize(backup.size),
          createdAt: backup.createdAt,
          modifiedAt: backup.modifiedAt
        }))
      }
    });
  } catch (error) {
    logger.error('Failed to get backup list:', error);
    res.status(500).json({
      success: false,
      message: '获取备份列表失败 / Failed to get backup list'
    });
  }
});

/**
 * 获取备份统计信息
 * GET /api/backup/stats
 */
router.get('/stats', adminOnly, async (req, res) => {
  try {
    const stats = await backupService.getBackupStats();
    
    res.json({
      success: true,
      data: {
        totalBackups: stats.totalBackups,
        totalSize: stats.totalSize,
        formattedTotalSize: backupService.formatFileSize(stats.totalSize),
        averageSize: stats.averageSize,
        formattedAverageSize: backupService.formatFileSize(stats.averageSize),
        oldestBackup: stats.oldestBackup,
        newestBackup: stats.newestBackup
      }
    });
  } catch (error) {
    logger.error('Failed to get backup statistics:', error);
    res.status(500).json({
      success: false,
      message: '获取备份统计失败 / Failed to get backup statistics'
    });
  }
});

/**
 * 创建新备份
 * POST /api/backup/create
 */
router.post('/create', adminOnly, async (req, res) => {
  try {
    logger.info(`Admin ${req.user.email} initiated manual backup`);
    
    const result = await scheduler.executeBackup();
    
    res.json({
      success: true,
      message: '备份创建成功 / Backup created successfully',
      data: {
        fileName: result.backup.fileName,
        size: result.backup.size,
        formattedSize: backupService.formatFileSize(result.backup.size),
        timestamp: result.backup.timestamp,
        verification: result.verification,
        cleanup: result.cleanup
      }
    });
  } catch (error) {
    logger.error('Manual backup failed:', error);
    res.status(500).json({
      success: false,
      message: '备份创建失败 / Backup creation failed',
      error: error.message
    });
  }
});

/**
 * 验证备份文件完整性
 * POST /api/backup/verify
 */
router.post('/verify', [
  adminOnly,
  body('fileName').notEmpty().withMessage('文件名不能为空 / File name is required')
], async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      message: '参数验证失败 / Parameter validation failed',
      errors: errors.array()
    });
  }

  try {
    const { fileName } = req.body;
    const backups = await backupService.getBackupList();
    const backup = backups.find(b => b.fileName === fileName);
    
    if (!backup) {
      return res.status(404).json({
        success: false,
        message: '备份文件不存在 / Backup file not found'
      });
    }

    const result = await backupService.verifyBackupIntegrity(backup.filePath);
    
    res.json({
      success: true,
      data: {
        fileName: fileName,
        valid: result.valid,
        error: result.error || null,
        size: result.size,
        formattedSize: result.size ? backupService.formatFileSize(result.size) : null,
        createdAt: result.createdAt
      }
    });
  } catch (error) {
    logger.error('Backup verification failed:', error);
    res.status(500).json({
      success: false,
      message: '备份验证失败 / Backup verification failed'
    });
  }
});

/**
 * 清理过期备份
 * POST /api/backup/cleanup
 */
router.post('/cleanup', adminOnly, async (req, res) => {
  try {
    logger.info(`Admin ${req.user.email} initiated backup cleanup`);
    
    const result = await backupService.cleanExpiredBackups();
    
    res.json({
      success: true,
      message: '备份清理完成 / Backup cleanup completed',
      data: {
        deletedCount: result.deletedCount,
        deletedSize: result.deletedSize,
        formattedDeletedSize: backupService.formatFileSize(result.deletedSize)
      }
    });
  } catch (error) {
    logger.error('Backup cleanup failed:', error);
    res.status(500).json({
      success: false,
      message: '备份清理失败 / Backup cleanup failed'
    });
  }
});

/**
 * 获取调度器状态
 * GET /api/backup/scheduler/status
 */
router.get('/scheduler/status', adminOnly, async (req, res) => {
  try {
    const status = scheduler.getTaskStatus();
    
    res.json({
      success: true,
      data: {
        tasks: status
      }
    });
  } catch (error) {
    logger.error('Failed to get scheduler status:', error);
    res.status(500).json({
      success: false,
      message: '获取调度器状态失败 / Failed to get scheduler status'
    });
  }
});

/**
 * 恢复数据库
 * POST /api/backup/restore
 */
router.post('/restore', [
  adminOnly,
  body('fileName').notEmpty().withMessage('备份文件名不能为空 / Backup file name is required'),
  body('createPreRestoreBackup').optional().isBoolean().withMessage('创建恢复前备份参数必须是布尔值 / Create pre-restore backup must be boolean'),
  body('confirmRestore').equals('true').withMessage('必须确认恢复操作 / Must confirm restore operation')
], async (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      message: '参数验证失败 / Parameter validation failed',
      errors: errors.array()
    });
  }

  try {
    const { fileName, createPreRestoreBackup = true } = req.body;
    
    logger.info(`Admin ${req.user.email} initiated database restore from: ${fileName}`);
    
    const result = await backupService.performRestore(fileName, {
      createPreRestoreBackup
    });
    
    res.json({
      success: true,
      message: '数据库恢复成功 / Database restore completed successfully',
      data: {
        restoredFrom: result.restoredFrom,
        preRestoreBackup: result.preRestoreBackup?.fileName,
        verification: result.verification,
        timestamp: result.timestamp
      }
    });
  } catch (error) {
    logger.error('Database restore failed:', error);
    res.status(500).json({
      success: false,
      message: '数据库恢复失败 / Database restore failed',
      error: error.message
    });
  }
});

/**
 * 获取恢复历史
 * GET /api/backup/restore/history
 */
router.get('/restore/history', adminOnly, async (req, res) => {
  try {
    const history = await backupService.getRestoreHistory();
    
    res.json({
      success: true,
      data: {
        history: history.map(item => ({
          id: item.id,
          backupFileName: item.backupFileName,
          backupSize: item.backupSize,
          formattedBackupSize: item.backupSize ? backupService.formatFileSize(item.backupSize) : null,
          success: item.success,
          preRestoreBackup: item.preRestoreBackup,
          verification: item.verification,
          error: item.error,
          timestamp: item.timestamp
        }))
      }
    });
  } catch (error) {
    logger.error('Failed to get restore history:', error);
    res.status(500).json({
      success: false,
      message: '获取恢复历史失败 / Failed to get restore history'
    });
  }
});

/**
 * 创建结构备份
 * POST /api/backup/schema
 */
router.post('/schema', adminOnly, async (req, res) => {
  try {
    logger.info(`Admin ${req.user.email} initiated schema backup`);
    
    const result = await backupService.createSchemaBackup();
    
    res.json({
      success: true,
      message: '结构备份创建成功 / Schema backup created successfully',
      data: {
        fileName: result.fileName,
        size: result.size,
        formattedSize: backupService.formatFileSize(result.size),
        timestamp: result.timestamp
      }
    });
  } catch (error) {
    logger.error('Schema backup failed:', error);
    res.status(500).json({
      success: false,
      message: '结构备份创建失败 / Schema backup creation failed',
      error: error.message
    });
  }
});

/**
 * 下载备份文件
 * GET /api/backup/download/:fileName
 */
router.get('/download/:fileName', adminOnly, async (req, res) => {
  try {
    const { fileName } = req.params;
    
    // 验证文件名格式
    if (!/^(backup_|schema_backup_)[\d\-T]+\.sql$/.test(fileName)) {
      return res.status(400).json({
        success: false,
        message: '无效的备份文件名 / Invalid backup file name'
      });
    }

    const backups = await backupService.getBackupList();
    const backup = backups.find(b => b.fileName === fileName);
    
    if (!backup) {
      return res.status(404).json({
        success: false,
        message: '备份文件不存在 / Backup file not found'
      });
    }

    // 验证文件完整性
    const verification = await backupService.verifyBackupIntegrity(backup.filePath);
    if (!verification.valid) {
      return res.status(400).json({
        success: false,
        message: '备份文件已损坏 / Backup file is corrupted',
        error: verification.error
      });
    }

    logger.info(`Admin ${req.user.email} downloaded backup: ${fileName}`);

    // 设置下载响应头
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
    res.setHeader('Content-Length', backup.size);

    // 发送文件
    res.sendFile(backup.filePath, (error) => {
      if (error) {
        logger.error('Failed to send backup file:', error);
        if (!res.headersSent) {
          res.status(500).json({
            success: false,
            message: '文件下载失败 / File download failed'
          });
        }
      }
    });
  } catch (error) {
    logger.error('Backup download failed:', error);
    res.status(500).json({
      success: false,
      message: '备份下载失败 / Backup download failed'
    });
  }
});

module.exports = router;